<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="评价项">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.evaluation_name"
                placeholder="输入评价项"></el-input>
            </el-form-item>
            <el-form-item label="关联品牌">
              <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.brand_id"
                placeholder="选择关联品牌">
                <el-option v-for="(item, index) in brandList" :key="item.id" :label="item.name" :value="index">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="门店类型">
              <el-select filterable @change="onSearch(1)" v-model="formSearch.store_id" placeholder="选择门店类型" clearable
                class="form-width">
                <el-option v-for="item in storeTypeList" :key="item.id" :label="item.store_type_name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="勘场类型">
              <el-select filterable @change="onSearch(1)" v-model="formSearch.survey_site" placeholder="选择勘场类型" clearable
                class="form-width">
                <el-option label="无需勘场" :value="1"></el-option>
                <el-option label="实地勘场" :value="2"></el-option>
                <el-option label="勘场出图" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="有效/无效">
                <el-select filterable @change="onSearch(1)" v-model="formSearch.is_invalid" placeholder="选择有效/无效" clearable
                  class="form-width">
                  <el-option label="有效" :value="1"></el-option>
                  <el-option label="无效" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="primary" @click="dialogFormVisible = true;"
            v-if="$isPer(permission, ['score_add'])">新增评分项</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选 <span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }} 数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
            v-if="$isPer(permission, ['score_add'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0" @click="delFunc"
            v-if="$isPer(permission, ['score_add'])">删除</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading">
        <el-table ref="table" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" height="100%" :data="tableData"
          highlight-selection-row border @selection-change="handleSelectionChange"
          @row-click="handleHighlightChangeTable">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="180px" prop="evaluation_name" label="评分项" show-overflow-tooltip></el-table-column>
          <el-table-column min-width="180px" prop="evaluation_name" label="关联品牌" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="scope.row.brand_id_arr.length == 0">--</div>
              <div v-else-if="scope.row.brand_id_arr.length == 1" class="row-box">
                <div class="row-item" v-for="(item, idx) in scope.row.brand_id_arr" :key="idx">
                  <div>{{ item.name }}</div>
                </div>
              </div>
              <div v-else class="row-box">
                <div v-if="!scope.row.is_brand_info" class="row-open" @click.stop="scope.row.is_brand_info = true">查看 <i
                    class="el-icon-arrow-down"></i></div>
                <template v-else>
                  <div class="row-item" v-for="(item, idx) in scope.row.brand_id_arr" :key="idx">
                    <div>{{ item.name }}</div>
                    <!-- <div style="border-left: 1px solid #f5f7fa;">{{ item.template_name }}</div> -->
                  </div>

                  <div class="row-close" @click.stop="scope.row.is_brand_info = false"><i class="el-icon-arrow-up"></i>
                  </div>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="180px" prop="evaluation_name" label="关联门店类型" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="scope.row.store_id_arr.length == 0">--</div>
              <div v-else-if="scope.row.store_id_arr.length == 1" class="row-box">
                <div class="row-item" v-for="(item, idx) in scope.row.store_id_arr" :key="idx">
                  <div>{{ item.name }}</div>
                </div>
              </div>
              <div v-else class="row-box">
                <div v-if="!scope.row.is_store_info" class="row-open" @click.stop="scope.row.is_store_info = true">查看 <i
                    class="el-icon-arrow-down"></i></div>
                <template v-else>
                  <div class="row-item" v-for="(item, idx) in scope.row.store_id_arr" :key="idx">
                    <div>{{ item.name }}</div>
                  </div>
                  <div class="row-close" @click.stop="scope.row.is_store_info = false"><i class="el-icon-arrow-up"></i>
                  </div>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="180px" prop="survey_site" label="关联勘场类型" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag v-if="scope.row.survey_site == 1" type="info">无需勘场</el-tag>
              <el-tag v-if="scope.row.survey_site == 2">实地勘场</el-tag>
              <el-tag v-if="scope.row.survey_site == 3">勘场出图</el-tag>
            </template>
          </el-table-column>
          <el-table-column min-width="180px" prop="is_invalid" label="有效/无效" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.is_invalid == 1 ? '有效' : '无效' }}</template>
          </el-table-column>
          <el-table-column min-width="180px" prop="created_at" label="创建时间" show-overflow-tooltip>
            <template slot-scope="scope">{{ $dateTimeToDate(scope.row.created_at) }}</template>
          </el-table-column>
          <el-table-column min-width="180px" prop="name" label="创建人" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog destroy-on-close :title="formType == 'add' ? '添加评分项' : '修改评分项'" :visible.sync="dialogFormVisible"
      :modal-append-to-body="false" @close="visibleClose" :close-on-click-modal="false" width="460px">
      <el-form :model="formData" :rules="formRules" class="user-info" ref="dialogFrom" label-width="110px"
        label-position="left">
        <el-form-item label="评分项" prop="name">
          <el-input v-model="formData.name" placeholder="请输入评分项" clearable></el-input>
        </el-form-item>
        <el-form-item label="关联品牌" prop="brand_idx_arr">
          <el-select v-model="formData.brand_idx_arr" multiple filterable placeholder="请选择品牌" clearable>
            <el-option v-for="(item, idx) in brandList" :key="item.id" :label="item.name" :value="idx">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门店类型" prop="store_idx_arr">
          <el-select v-model="formData.store_idx_arr" multiple filterable placeholder="请选择门店类型" clearable>
            <el-option v-for="(item, idx) in storeTypeList" :key="item.id" :label="item.store_type_name" :value="idx">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="勘场类型">
          <el-select filterable v-model="formData.survey_site" placeholder="请选择勘场类型" clearable>
            <el-option label="无需勘场" :value="1"></el-option>
            <el-option label="实地勘场" :value="2"></el-option>
            <el-option label="勘场出图" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit" :loading="submitBtn">提交</el-button>
        <el-button @click="visibleClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import scoreApi from '@/api/scoreApi'
import brandApi from '@/api/brandApi'
import storeTypeApi from '@/api/storeTypeApi'

export default {
  name: "score",
  data() {
    return {
      tableLoading: false,//列表loading
      tableData: [],//列表数据
      formSearch: {
        evaluation_name: '',
        brand_id: '',
        store_id: '',
        survey_site: '',
        is_invalid: ''
      },//搜索form
      moreSearchShow: false,//
      showOpne: false,//
      page: 1,
      num: 10,
      total: 0,
      multipleSelection: [],//多选数据

      // 弹窗
      storeTypeList: [],
      brandList: [],

      formType: 'add',
      dialogFormVisible: false,
      submitBtn: false,
      formData: {
        id: '',
        name: '',
        brand_idx_arr: [],
        store_idx_arr: [],
        survey_site: '',
      },
      formRules: {
        name: [{ required: true, message: "请输入门店类型", trigger: "change" }],
        brand_idx_arr: [{ required: true, message: "请选择品牌", trigger: "change" }],
        store_idx_arr: [{ required: true, message: "请选择门店类型", trigger: "change" }],
      },
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })

    this.getList();
    this.getBrandList();
    this.getStoreTypeList();
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    addFunc() { },
    editFunc() {
      let info = this.multipleSelection[0];
      console.log(info)
      let formData = this.formData;
      let brandList = this.brandList
      let storeTypeList = this.storeTypeList
      let brand_idx_arr = []
      let store_idx_arr = []
      info.brand_id_arr.map(item => {
        brandList.map((row, idx) => {
          if (item.id == row.id) {
            brand_idx_arr.push(idx)
          }
        })
      })
      info.store_id_arr.map(item => {
        storeTypeList.map((row, idx) => {
          if (item.id == row.id) {
            store_idx_arr.push(idx)
          }
        })
      })

      this.formData = {
        id: info.id,
        name: info.evaluation_name,
        brand_idx_arr,
        store_idx_arr,
        survey_site: info.survey_site,
      }
      this.formType = 'edit'
      this.dialogFormVisible = true
    },
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let id_arr = multipleSelection.map(item => item.id)
      let name_arr = multipleSelection.map(item => item.evaluation_name)
      this.$confirm('是否删除【' + name_arr.join(', ') + '】?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(id_arr)
        scoreApi.delEvaluationConfig({ id_arr }).then((res) => {
          console.log(res, "delEvaluationConfig");
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.onSearch();
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });

    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },

    /*****************弹窗******************/
    visibleClose() {
      this.$refs['dialogFrom'].resetFields();
      this.formData.survey_site = ''
      this.dialogFormVisible = false;
    },
    saveSubmit() {
      this.$refs['dialogFrom'].validate((valid) => {
        if (valid) {
          this.submitBtn = true
          let formData = this.formData;
          let brandList = this.brandList
          let storeTypeList = this.storeTypeList
          let brand_id_arr = [], store_id_arr = []
          formData.brand_idx_arr.map(idx => {
            let item = brandList[idx]
            brand_id_arr.push({
              id: item.id,
              name: item.name
            })
          })
          formData.store_idx_arr.map(idx => {
            let item = storeTypeList[idx]
            store_id_arr.push({
              id: item.id,
              name: item.store_type_name
            })
          })
          if (this.formType == 'add') {
            scoreApi.addEvaluationConfig({
              evaluation_name: formData.name,
              brand_id_arr,
              store_id_arr,
              survey_site: formData.survey_site
            }).then(res => {
              console.log(res, '新增评分项')
              if (res.code == 200) {
                this.visibleClose()
                this.onSearch(1)
              } else {
                this.$message.warning(res.message)
              }
              this.submitBtn = false
            })
          } else {
            scoreApi.updEvaluationConfig({
              id: formData.id,
              evaluation_name: formData.name,
              brand_id_arr,
              store_id_arr,
              survey_site: formData.survey_site
            }).then(res => {
              console.log(res, '更新评分项')
              if (res.code == 200) {
                this.visibleClose()
                this.onSearch()
              } else {
                this.$message.warning(res.message)
              }
              this.submitBtn = false
            })
          }
        } else {
          return false;
        }
      });
    },
    /*****************end******************/
    // 获取列表数据
    getList() {
      this.loading = true;
      let formSearch = this.formSearch
      scoreApi.getEvaluationConfigList({
        page: this.page,
        num: this.num,
        evaluation_name: formSearch.evaluation_name,
        brand_id: formSearch.brand_id,
        survey_site: formSearch.survey_site,
        store_id: formSearch.store_id,
        is_invalid: formSearch.is_invalid
      }).then((res) => {
        console.log(res, "获取评分项");
        this.loading = false;
        if (res.code == 200) {
          res.data.list.map(item => {
            item.brand_id_arr = JSON.parse(item.brand_id_arr)
            item.is_brand_info = false
            item.store_id_arr = JSON.parse(item.store_id_arr)
            item.is_store_info = false
          })
          console.log(res.data.list, '获取评分项2')
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: "warning",
        });
      });
    },
    // 获取品牌
    getBrandList() {
      brandApi.getBrandList({
        page: 1,
        num: 999,
      }).then(res => {
        console.log(res, "品牌列表")
        if (res.code == 200) {
          this.brandList = res.data.list;
        }
      })
    },
    // 获取门店类型
    getStoreTypeList() {
      storeTypeApi.getStoreTypeList({
        page: 1,
        num: 999,
      }).then((res) => {
        console.log(res, "获取门店列表");
        if (res.code == 200) {
          this.storeTypeList = res.data.list;
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>